import React, { useState, useEffect, FC } from 'react'
import { WaterMark } from '@ant-design/pro-layout';
import ImgCrop from 'antd-img-crop';
import { Upload, message, Modal } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import 'antd/es/modal/style';
import 'antd/es/slider/style';
import './index.less'
import { getBase64, insertStr } from '@/utils/utils'
import { getUpPic } from './service'

export type cropOptionsType = {
    modalTitle?: string,
    modalWidth?: number,
    aspect?: number,
    rotate?: boolean,
    shape?: string,
    grid?: boolean,
    fillColor?: string
}
type UploadImageProps = {
    cropOptions?: cropOptionsType,
    imgNum?: number,
    isModal?: boolean,
    imageList?: any,
    onAdImageListChange: (values: ImageListType[]) => void,
}
export type ImageListType = {
    uid: string,
    name: string,
    status: string,
    url: string,
}
const UploadImage: FC<UploadImageProps> = (props) => {
    const [loading, setLoading] = useState<boolean>(false);
    const [fileList, setFileList] = useState<any>([]);
    const [previewVisible, setPreviewVisible] = useState<boolean>(false);
    const [previewTitle, setPreviewTitle] = useState<string>();
    const [previewImage, setPreviewImage] = useState<string>();


    const { cropOptions, imgNum = 1, isModal = false, imageList = undefined, onAdImageListChange } = props

    /**
     * 
     * @param file 文件限制
     * @returns 
     */
    const beforeUpload = (file: File | any) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('图片格式不支持，请上传jpg或者png格式!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('上传头像图片大小不能超过 2MB!');
        }
        if (isJpgOrPng && isLt2M) {
            getBase64(file, async (imageUrl: any) => {
                const response = await getUpPic({ img_type: "testUp", img_byte: imageUrl });
                setLoading(false)
                if (response && response instanceof Object) {
                    if (imageList === undefined) {
                        const newFileList = [...fileList, {
                            uid: file.uid,
                            name: file.name,
                            status: 'done',
                            url: response.data,
                        }]
                        setFileList(newFileList)
                        onAdImageListChange(newFileList)
                    } else {
                        const newFileList = [...imageList, {
                            uid: file.uid,
                            name: file.name,
                            status: 'done',
                            url: response.data,
                        }]
                        onAdImageListChange(newFileList)
                    }
                }
            });
        }
        return isJpgOrPng && isLt2M;
    }

    const handleChange = (info: any) => {
        if (info.file.status === 'uploading') {
            setLoading(true)
            return;
        }
    };

    const onRemove = (file: any) => {
        if (imageList === undefined) {
            fileList.splice(fileList.findIndex((item: ImageListType) => item.uid === file.uid), 1)
            setFileList([...fileList])
            onAdImageListChange([...fileList])
        }else{
            imageList.splice(imageList.findIndex((item: ImageListType) => item.uid === file.uid), 1)
            onAdImageListChange([ ...imageList])
        }
    }
    const handlePreview = (file: any) => {
        if (file.url) {
            if (isModal) {
                setPreviewVisible(true)
                setPreviewTitle(file.name)
                setPreviewImage(file.url)
            } else {
                let div = document.createElement("div");
                const image = new Image();
                image.src = file.url;
                div.appendChild(image)
                const imgWindow = window.open(file.url);
                const divStr = insertStr(div.outerHTML, 4, ` style="text-align: center;height: 100%;"`)
                imgWindow?.document.write(insertStr(divStr, (divStr.length - 7), ` style="text-align: center;height: 80%;margin-top:5%;"`));
            }
        }
    }

    const handleCancel = () => {
        setPreviewVisible(false)
    }

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }} className='upload-image-desc'>上传图片</div>
        </div>
    );
    const cropProps: any = {
        modalTitle: "上传图片", //弹窗标题
        modalWidth: 600, //弹窗宽度
        aspect: 1 / 1,
        rotate: true,
        shape: "rect",
        grid: true,
        fillColor: '#000000'
    };
    return (
        <WaterMark content="御码科技" className="upload-image">
            <ImgCrop {...cropProps} {...cropOptions}>
                <Upload
                    listType="picture-card"
                    accept="image/*"
                    className="avatar-uploader"
                    fileList={(
                        imageList === undefined ? [...fileList] : [...imageList]
                    )}
                    beforeUpload={beforeUpload}
                    onChange={handleChange}
                    onRemove={onRemove}
                    onPreview={handlePreview}
                >
                    {(imageList === undefined ? fileList.length : imageList.length) >= imgNum ? null : uploadButton}
                </Upload>
            </ImgCrop>
            <Modal
                visible={previewVisible}
                title={previewTitle}
                footer={null}
                onCancel={handleCancel}
            >
                <img alt={previewTitle} style={{ width: '100%' }} src={previewImage} />
            </Modal>
        </WaterMark>
    );
}

export default UploadImage;